package org.ala.tiktools.rocketmq;

import org.springframework.core.env.Environment;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author ala
 * @date 2024-12-03 13:51
 */
public class ConfigValueUtils {


    /**
     *  配置项的正则
     *  <p> 字母 | 数字 | 下划线 | .
     */
    static Pattern KP = Pattern.compile("\\$\\{[\\w+\\.?]+\\}");
    /**
     *  解析配置名中的配置项
     *  <p> aaaa-${aaaa}，会解析出所有的${aaaa}
     */
    public static Set<String> parseConfigItem(String str) {
        Set<String> set = new HashSet<>();
        Matcher m = KP.matcher(str);
        while (m.find()) {
            set.add(m.group());
        }
        return set;
    }
    /**
     *  替换str中的配置部分
     */
    public static String replaceConfigItem(String str, Environment env) {
        Set<String> ks = parseConfigItem(str);
        Map<String, String> kvs = ks.stream().collect(Collectors.toMap(k->k, item->{
                String k = item.substring(2, item.length()-1);
                String v = env.getProperty(k);
                if (v == null) {
                    v = k;
                }
                return v;
            }, (o,n)->n));
        for (Map.Entry<String, String> e : kvs.entrySet()) {
            str = str.replaceAll(e.getKey(), e.getValue());
        }
        return str;
    }
}
